# == Schema Information
# Schema version: 38
#
# Table name: events
#
#  id           :integer(11)     not null, primary key
#  title        :string(255)
#  category     :integer(11)
#  start_at     :datetime
#  end_at       :datetime
#  location     :string(255)
#  content      :text
#  content_html :text
#  school_id    :integer(11)
#  submitor_id  :integer(11)
#  is_closed    :boolean(1)
#  is_hidden    :boolean(1)
#  created_at   :datetime
#  updated_at   :datetime
#  ref          :string(255)
#

class Event < ActiveRecord::Base
  cattr_reader :per_page
  @@per_page = 10
  
  belongs_to :submitor, :class_name => 'User', :foreign_key => 'submitor_id'
  belongs_to :school
  has_one    :pic, :class_name => 'EventPic', :dependent => :destroy
  has_many   :participation, :dependent => :destroy
  has_many   :participators, :through => :participation, :source => :user
  has_many   :comments, :class_name => "EventComment", :dependent => :destroy
  has_many   :photos
  
  validates_presence_of :title, :category, :start_at, :end_at, :location
  
  format_attribute :content
  
  def self.recent(limit = 10)
    self.find(:all,
              :conditions => "events.end_at > now()",
              :order => "events.start_at desc, events.end_at desc",
              :include => [:submitor, :pic],
              :limit => limit)
  end
  
  def self.categories
    %w(公益旅游 物资募捐 支教 其他)
  end
  
  def editable_by?(user)
    user!=:false && (submitor_id == user.id || user.is_admin?)
  end

  def has_end?()
    end_at < Time.now
  end
  
  def self.archives
    date_func = "extract(year from created_at) as year,extract(month from created_at) as month"
    
    counts = Event.find_by_sql(["select count(*) as count, #{date_func} from events where created_at < ? group by year,month order by year asc,month asc",Time.now])
    
    sum = 0
    result = counts.map do |entry|
      sum += entry.count.to_i
      {
        :name => entry.year + "年" + entry.month + "月",
        :month => entry.month.to_i,
        :year => entry.year.to_i,
        :delta => entry.count,
        :sum => sum
      }
    end
    return result.reverse
  end
=begin  
  # deprecated
  def self.recent_cloud
    find(:all, :order => "events.start_at desc, count desc",
                               :joins => "left join participations on events.id=participations.event_id",
                               :group => "events.id",
                               :select => "events.id, events.title, count(events.id) as count",
                               :limit => 10)
  end
=end
end
